package mdb

import (
	"fmt"
	"gitee.com/dennis-mxx/mxx-core/mreflect"
	"strings"
)

var Insert insert

type insert struct {
	insertSql strings.Builder
	params    []interface{}
	tableName string
}

func NewInsert(tableName string) *insert {
	var slice []interface{}
	insert := insert{insertSql: strings.Builder{}, params: slice, tableName: tableName}
	return &insert
}

func (domain *insert) Insert(entity interface{}) string {
	dataMap := mreflect.StructDBTagMap(entity)

	insertSql := domain.insertSql
	paramSql := strings.Builder{}

	insertSql.WriteString("insert into ")
	insertSql.WriteString(domain.tableName)
	insertSql.WriteString("( ")

	len := len(dataMap) - 1
	i := 0
	for k, v := range dataMap {
		domain.params = append(domain.params, v)
		insertSql.WriteString(k)
		paramSql.WriteString("?")
		if i < len {
			insertSql.WriteString(",")
			paramSql.WriteString(",")
		}
		i++
	}
	insertSql.WriteString(fmt.Sprintf(") values (%s)", paramSql.String()))
	return insertSql.String()
}
func (domain *insert) Params() []interface{} {
	return domain.params
}
